package com.zhiyou.aifeng.module_login

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import cn.jpush.android.api.JPushInterface
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.zhiyou.aifeng.common.base.oneClick
import com.zhiyou.aifeng.common.helper.*
import com.zhiyou.aifeng.common_ui.base.BaseActivity
import com.zhiyou.aifeng.common_ui.base.setCompoundDrawable
import com.zhiyou.aifeng.common_ui.router.Routers
import com.zhiyou.aifeng.common_ui.utils.*
import com.zhiyou.aifeng.viewmodel.LoginViewModel
import kotlinx.android.synthetic.main.login_activity_login.*
import org.jetbrains.anko.sdk25.listeners.onFocusChange
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.toast
import org.json.JSONObject

@Route(path = Routers.login)
class LoginActivity : BaseActivity() {

    @JvmField
    @Autowired(name = "offLine")
    var isOffLine: Boolean = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        ARouter.getInstance().inject(this)
        setContentView(R.layout.login_activity_login)
        setTransparentAndToolbar()
        initTitle()

        login_account.requestFocus()
    }

    override fun getViewModel() = get<LoginViewModel>()

    override fun initTitle(title: String, name: String, divider: Boolean) {
        if (isOffLine) {
            isLogin = false
            clearShared(
                "userId",
                "userName",
                "userHead",
                "realName",
                "balance",
                "auth",
                "serviceTel",

                "idCard",
                "authRegion",
                "authAdress",
                "authGroup",
                "authFront",
                "authBack"
            )
            ActivityStack.screenManager.popAllActivityExcept(LoginActivity::class.java)
        }

        if (getString("phone").isNotBlank()) {
            login_account.setText(getString("phone"))
            login_account.setSelection(login_account.text.length)
        }

        login_check.setCompoundDrawable(
            leftDrawable = R.drawable.login_agree_selector,
            leftSize = 17f
        )
        bt_apply.setCompoundDrawable(
            rightDrawable = R.mipmap.login_apply_in,
            rightSize = 15f
        )

        login_account.apply {
            onFocusChange { _, hasFocus ->
                login_account.setBackgroundResource(
                    if (hasFocus) R.drawable.rec_bg_white_stroke_49c595_r6
                    else R.drawable.rec_bg_white_stroke_d8d8d8_r6
                )
            }
        }
        login_yzm.apply {
            onFocusChange { _, hasFocus ->
                view6.setBackgroundResource(
                    if (hasFocus) R.drawable.rec_bg_white_stroke_49c595_r6
                    else R.drawable.rec_bg_white_stroke_d8d8d8_r6
                )
            }
        }

        bt_apply.oneClick { startActivity<ApplyActivity>() }
        login_deal.oneClick {
            ARouter.getInstance()
                .build(Routers.deal)
                .withString("title", "平台使用协议")
                .navigation()
        }
    }

    @SuppressLint("SetTextI18n")
    override fun doClick(v: View) {
        super.doClick(v)
        when (v.id) {
            R.id.bt_yzm -> {
                when {
                    login_account.text.isBlank() -> {
                        login_account.requestFocus()
                        toast("请输入手机号")
                        return
                    }
                    !login_account.text.isMobile() -> {
                        login_account.requestFocus()
                        toast("请输入正确的手机号")
                        return
                    }
                }

                getViewModel().getCode(login_account.textString())
                    .bindLifeCycle(getLifecycleOwner())
                    .subscribeByNoErrorWithException(
                        event = getViewModel(),
                        onSuccess = {
                            toast("验证码发送成功！")

                            getViewModel().countDown(count = 60)
                                .bindLifeCycle(getLifecycleOwner())
                                .subscribeBy(
                                    onNext = {
                                        bt_yzm.text = "${60 - it}s后重试"
                                        bt_yzm.isClickable = false
                                    },
                                    onComplete = {
                                        bt_yzm.text = "重新获取"
                                        bt_yzm.isClickable = true
                                    }
                                )
                        },
                        onException = {
                            showHintDialog(
                                hint = "您还未申请加入东方红车队，是否立即申请？",
                                sure = "申请"
                            ) { startActivity<ApplyActivity>() }
                        }
                    )
            }
            R.id.bt_login -> {
                when {
                    login_account.text.isBlank() -> {
                        login_account.requestFocus()
                        toast("请输入手机号")
                        return
                    }
                    login_yzm.text.isBlank() -> {
                        login_yzm.requestFocus()
                        toast("请输入验证码")
                        return
                    }
                    !login_account.text.isMobile() -> {
                        login_account.requestFocus()
                        toast("请输入正确的手机号")
                        return
                    }
                    !login_check.isChecked -> {
                        toast("请阅读并同意平台相关规定")
                        return
                    }
                }

                getViewModel().login(
                    login_account.textString(),
                    login_yzm.textString(),
                    JPushInterface.getRegistrationID(baseContext)
                )
                    .bindLifeCycle(getLifecycleOwner())
                    .subscribeByNoError(
                        event = getViewModel(),
                        onSuccess = {
                            val obj = JSONObject(it)
                            putShared("phone", obj.optNotNull("phone"))
                            putShared("userId", obj.optNotNull("id"))
                            putShared("userName", obj.optNotNull("nickname"))
                            putShared("userHead", obj.optNotNull("avatar"))
                            putShared("realName", obj.optNotNull("realname"))
                            putShared("balance", obj.optNotNull("userBalance").formatDecimal())
                            putShared("auth", obj.optNotNull("realAuthStatus"))

                            isLogin = true
                            ARouter.getInstance().build(Routers.main).navigation()
                            finishView()
                        }
                    )
            }
        }
    }

}